package code;

import java.util.ArrayList;
import java.util.List;

public class Code23 {
	
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode head = null,p;
        int n=lists.length;
        ListNode[] pIdx=new ListNode[n];
        int i,j;
        for(i=0;i<n;i++){
        	pIdx[i]=lists[i];
        }
        p=null;
        while(true){
        	ListNode minNode=null;
        	int idx=0;
        	for(i=0;i<n;i++){
        		if(pIdx[i]==null)
        			continue;
        		if(minNode==null || minNode.val>pIdx[i].val){
        			idx=i;
        			minNode=pIdx[i];
        		}
        	}
        	if(minNode==null)
        		break;
        	if(head==null){
        		head=minNode;
        		p=minNode;
        	}
        	else{
	        	p.next=minNode;
	        	p=minNode;
        	}
        	pIdx[idx]=pIdx[idx].next;
        }
        return head;
    }
    public static void main(String[] args){
    	ListNode[] lists=new ListNode[1];
    	lists[0]=new ListNode(1);
    	new Code23().mergeKLists(lists);
    }
}
